/*
 * cafe-toolsbar.js
 * @Author :      GUORUI
 * @CreateDate :  2017年8月22日
 * Copyright (c) 2017, NRIET.　
 * 辅助工具条控件
 */
;
define(function () {
    //创建主界面
    function bulidHtml(cfg) {
        var $warp = $('<div>').addClass('cafe-busis-toolsbar');
        if (cfg.barList.menubar) {
            var $l = $("<div>").addClass('cafe-busis-toolsbar-left');
            var $u = $('<ul>');
            $.each(cfg.barList.menubar, function (i, o) {
                if (o.isHide) return;
                var $btn = $('<li>').attr("id", o.id).attr("index", i).addClass(o.icon).text(o.name);
                $u.append($btn);
            })
            $l.append($u);
        }
        if (cfg.barList.toolsbar) {
			debugger;
            var $r = $("<div>").addClass('cafe-busis-toolsbar-right');
            var $u = $('<ul>');
            $.each(cfg.barList.toolsbar, function (i, o) {
                var $btn = $('<li>').attr("id", o.id).addClass(o.icon).text(o.name);
                if (o.isHide) $btn.hide();
                if (o.isDef) {
                    $btn.addClass("active");
                }
                if (o.child) {
                    var $div = $('<div>').addClass(o.childCls);
                    $.each(o.child, function () {
                        var $gspan = $('<span>').attr("gid", this.id).text(this.text);
                        if (this.isDef) {
                            $gspan.addClass("active");
                        }
                        $div.append($gspan);
                    });
                    $btn.append($div.hide());
                }
                switch (o.id) {
                    case "location":
                        var $g = $('<div>').addClass("cafe-at-location");
                        $.each([
                            { id: "china", isDef: false, text: "中国" },
                            { id: "hb", isDef: false, text: "华北" },
                            { id: "hh", isDef: false, text: "海河" },
                            { id: "tj", isDef: true, text: "天津" }
                        ], function () {
                            var $gspan = $('<span>').attr("gid", this.id).text(this.text);
                            if (this.isDef) {
                                $gspan.addClass("active");
                            }
                            $g.append($gspan);
                        });
                        $btn.append($g.hide());
                        break;
					case "layerManager":
                        var $g = $('<div>').addClass("cafe-at-layerManager");
                        $.each([
							{
								id:"area",text:"分区",children:[
									{ id: "H9", isDef: false, text: "9分区",isDraw:true,type:'Area',layerID:'arealayer',category:'radio'},
									{ id: "H11", isDef: false, text: "11分区",isDraw:true,type:'Area',layerID:'arealayer',category:'radio' },
									{ id: "H32", isDef: false, text: "32分区",isDraw:true ,type:'Area',layerID:'arealayer',category:'radio'},
									{ id: "H77", isDef: false, text: "77分区",isDraw:true,type:'Area',layerID:'arealayer',category:'radio' },
								]
							},
							{
								id:"sate",text:"卫星",children:[
									{ id: "satellite_china", isDef: false, text: "卫星",type:'satellite',category:'radio' }
								]
							},
							{
								id:"river",text:"河流",children:[
									{ id: "R12", isDef: false, text: "一二级",isDraw:true,type:'river1',layerID:'river1',category:'check' },
									{ id: "R4", isDef: false, text: "三级",isDraw:true,type:'river3',layerID:'river3',category:'check' },
									{ id: "R5", isDef: false, text: "四级",isDraw:true,type:'river4',layerID:'river4',category:'check' }
								]
							}
                        ], function () {
							var $parentDIV = $('<div>').attr("gid", this.id).append($("<div>").addClass("layerpartnt").text(this.text));
							let sondiv = this.children;
							let soncontain = $("<div>").addClass("layerson")
							for(let i = 0;i<sondiv.length;i++){
								var $gspan = $('<span>').attr("gid", sondiv[i].id).attr("isDraw", sondiv[i].isDraw).attr("category", sondiv[i].category).attr("layerID", sondiv[i].layerID).attr("type", sondiv[i].type).text(sondiv[i].text);
								if (sondiv[i].isDef) {
									$gspan.addClass("active");
								}
								soncontain.append($gspan);
							}
							$parentDIV.append(soncontain);
							$g.append($parentDIV);
                        });
                        $btn.append($g.hide());
                        break;
                    case "station":
                        var $g = $('<div>').addClass("cafe-at-station");
                        $.each([
                            { id: "-1", isDef: false, text: "全部站" },
                            { id: "0", isDef: true, text: "基本站" },
                            { id: "1", isDef: true, text: "区域站" },
                            { id: "2", isDef: false, text: "海岛站" },
                            { id: "3", isDef: false, text: "浮标站" },
                            { id: "4", isDef: false, text: "船舶站" },
                            { id: "5", isDef: false, text: "平台站" },
                            { id: "6", isDef: false, text: "微智站" }
                        ], function () {
                            var $gspan = $('<span>').addClass("cas-station").attr("type", this.id).text(this.text);
                            if (this.isDef) {
                                $gspan.addClass("active");
                            }
                            $g.append($gspan);
                        });
                        $btn.append($g.hide());
                        break;
                    case "gistools":
                        var $g = $('<div>').addClass("cafe-at-gistools");
                        $.each([
                            { id: "enlarge", isDef: false, text: "放大" },
                            { id: "narrow", isDef: false, text: "缩小" },
                            { id: "distance", isDef: false, text: "测距" },
                            { id: "area", isDef: false, text: "测面积" },
                            { id: "border", isDef: true, text: "边界" },
                            { id: "mask", isDef: false, text: "掩膜" },
                            // { id: "changemap", isDef: false, text: "地图切换" },
                            { id: "zcd", isDef: false, text: "中尺度" },
                            { id: "windbar", isDef: true, text: "风羽" },
                            { id: "windspeed", isDef: true, text: "风速" },
                        ], function () {
                            var $gspan = $('<span>').addClass(this.id).attr("gid", this.id).text(this.text);
                            if (this.isDef) {
                                $gspan.addClass("active");
                            }
                            $g.append($gspan);
                        });
                        $btn.append($g.hide());
                        break;
                }
                $u.append($btn);
            })
            $r.append($u);
        }
        $warp.append($l).append($r)
        return $warp;
    }
    /**
     * 按钮点击处理
     */
    function btnHandle($that, cfg) {
        switch ($that.attr("id")) {
            case "location": //快速定位
			case "layerManager":
            case "station": //站点选择
            case "gistools":
                $that.siblings().find("div").hide();
                $that.siblings().removeClass("active")
                if ($that.hasClass("active")) {
                    $that.find("div").show();
                } else {
                    $that.find("div").hide();
                }
                if ($(".zcd").hasClass('active')) {
                    $(".zcd.active").click();
                    GLMap.getLayer("drawSvg").endDraw();
                    GLMap.enablePan();
                }
                break;
            case "zcd":
                if ($that.hasClass('active')){
                    if (CafeJS.ModalBoxExist('zcdModal')) {
                        CafeJS.ModalBoxClose('zcdModal');
                        return;
                    }
                    CafeJS.ModalBox({
                        id: $that.attr("id"),
                        container: 'cafe-busis-container',
                        title: "中尺度",
                        width: 565,
                        m_top: 90,
                        m_right: 100,
                        hide: true,
                        url:'/business/template/zcdModal.html',
                        closed: function () {
                            $that.removeClass("active");
                            CafeJS.ModalBoxClose('zcdModal');
                        }
                    });
                }else{
                    CafeJS.ModalBoxHide(id);
                }
                    
                break;
            case "layer":
                if ($that.hasClass('active'))
                    $('#c-b-layermanage').show();
                else
                    $('#c-b-layermanage').hide();
                break;
            default:
                if ($.isFunction(cfg.call)) {
                    cfg.call($that.attr("id"), $that.hasClass("active"), $that.attr("index"));
                }
                break;
        }
    }
    /**
     * 绑定事件
     */
    function _eves($drop, cfg) {
        $drop.off().on("click", ".cafe-busis-toolsbar-left li", function () {
            if (!$(this).hasClass("disabled")) {
                if (!$(this).hasClass("active")) {
                    $(this).addClass("active").siblings().removeClass('active');
                    btnHandle($(this), cfg);
                }
            }
        }).on("click", ".cafe-busis-toolsbar-right li", function () {
            if (!$(this).hasClass("disabled")) {
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");
                } else {
                    $(this).addClass("active");
                }
                btnHandle($(this), cfg);
            }
        }).on("click", ".cafe-at-child>span", function (e) {
            e.stopPropagation();
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
            } else {
                $(this).addClass("active");
            }
            $(this).attr('id', $(this).attr('gid'));
            btnHandle($(this), cfg);
        }).on("click", ".cafe-at-location>span", function (e) { //快速定位
            e.stopPropagation();
            $(this).addClass("active").siblings().removeClass('active');
            var type = $(this).attr("gid");
            switch (type) {
                case "china": //中国
                    GIS.Extent.Set(cfg.gisId, { xmin: 135, xmax: 80, ymax: 55, ymin: 15 });
                    break;
                case "hb": //华北
                    GIS.Extent.Set(cfg.gisId, { xmin: 109.72, xmax: 123.70, ymax: 43.77, ymin: 33.39 });
                    break;
                case "hh": //海河
                    GIS.Extent.Set(cfg.gisId, { xmin: 108.71, xmax: 123.66, ymax: 43.88, ymin: 35.55 });
                    break;
                case "tj": //天津
                    GIS.Extent.Set(cfg.gisId, { xmin: 114.94, xmax: 119.80, ymax: 40.47, ymin: 38.32 });
                    break;
            }

        }).on("click", ".cafe-at-layerManager span", function (e) {
            e.stopPropagation();
			debugger
			var type = $(this).attr("type");
			if($(this).hasClass("active")){
				 $(this).removeClass("active");
			}else{
				 $(".cafe-at-layerManager span[type='"+type+"'].active").click();
				 $(this).addClass("active");
			}
            var gid = $(this).attr("gid");
			if($(this).attr("isDraw")){
				drawlyboundry($(this).hasClass("active"),gid,cfg,$(this).attr("layerID"));
			}else{
				controllayer($(this).hasClass("active"),gid,cfg)
			}
			
        }).on("click", ".cafe-at-gistools>span", function (e) { //gis工具
            e.stopPropagation();
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
            } else {
                $(this).addClass("active");
            }
            var type = $(this).attr("gid");
            switch (type) {
                case "enlarge": //放大
                    $(this).removeClass("active");
                    GIS.Extent.Zoom(cfg.gisId, true);
                    break;
                case "narrow": //缩小
                    $(this).removeClass("active");
                    GIS.Extent.Zoom(cfg.gisId, false);
                    break;
                case "distance"://距离
                    $(".area").removeClass('active');
                    GIS.Measure({
                        id: "at-gis",
                        type: "area",
                        status: "end",
                        GLMap: mapObj[cfg.gisId]
                    });
                    GIS.Measure({
                        id: "at-gis",
                        type: "distance",
                        status: $(this).hasClass("active") ? "start" : "end",
                        GLMap: mapObj[cfg.gisId]
                    });
                    break;
                case "area"://面积
                    $(".distance").removeClass('active');
                    GIS.Measure({
                        id: "at-gis",
                        type: "area",
                        status: "end",
                        GLMap: mapObj[cfg.gisId]
                    });
                    GIS.Measure({
                        id: "at-gis",
                        type: "area",
                        status: $(this).hasClass("active") ? "start" : "end",
                        GLMap: mapObj[cfg.gisId]
                    });
                    break;
                case "changemap"://切换地图
                    if ($(this).hasClass('active'))
                        GIS.Common.changeBaseLayer(cfg.gisId, 'online_WGS84', null);
                    else
                        GIS.Common.changeBaseLayer(cfg.gisId, 'quanguo_WGS84', null);
                    break;
                case "border":
                    if ($(this).hasClass('active'))
                        GIS.Graphic.drawBoundary(cfg.gisId,"tjMapborderLayer",'12',{'strokeStyle':'rgba(0,0,0,1)','lineWidth':3})
                    else
                        GIS.LayerControll.deleteLayer(cfg.gisId,"tjMapborderLayer")
                    break;
                case "mask":
                    if ($(this).hasClass('active'))
                        GIS.Common.yanmo(cfg.gisId,"tjMapyanmoLayer",'12',{'strokeStyle':'rgba(255,255,255,1)'})
                    else
                        GIS.LayerControll.deleteLayer(cfg.gisId,"tjMapyanmoLayer")
                    break;
                case "zcd":
                    $(this).attr('id', $(this).attr('gid'));
                    debugger;
                    btnHandle($(this), cfg);
                    break;
                case "windbar":     //风羽
                    if (!$(this).hasClass('active')){
                        windBarControl(false, cfg);
                    }else{
                        windBarControl(true, cfg);
                    }
                    break;
                case "windspeed":   //风速
                    if (!$(this).hasClass('active')){
                        windSpeedControl(false, cfg);
                    }else{
                        windSpeedControl(true, cfg);
                    }
                    break;
            }
        }).on("click", ".cas-station", function (e) { //站点选择
            e.stopPropagation();
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
            } else {
                $(this).addClass("active");
            }
            var type = $(this).attr("type");
            var isSel = $(this).hasClass("active");
            if (type == -1) { // 全选
				$drop.find('.cas-station').each(function (i, item) {
					if (i === 0) return;
					if ((isSel && !$(item).hasClass('active')) ||
						(!isSel && $(item).hasClass('active')))
						$(item).trigger('click');
				})
				return;
            }
            var isAllSelected = true;
			$drop.find('.cas-station').each(function (i, item) {
				if (i === 0) return;
				if (!$(item).hasClass('active'))
					isAllSelected = false;
			})
			if (isAllSelected) {
				$drop.find('.cas-station').first().addClass('active');
			} else {
				$drop.find('.cas-station').first().removeClass('active');
			}

            if (type === '6' && isSel && CafeJS.autostat.queryWZElementList) {
                CafeJS.autostat.queryWZElementList();
            }
            
            GIS.Station.eleShowControl(cfg.gisId, [type], CafeJS.layerManage.getEleType(), isSel ? 'show' : 'hide');

            if (!isSel) return;
            if ($(".cafe-at-gistools .windbar").hasClass('active')) {
                windBarControl(true, cfg);
            } else {
                windBarControl(false, cfg);
            }
            if ($(".cafe-at-gistools .windspeed").hasClass('active')) {
                windSpeedControl(true, cfg);
            } else {
                windSpeedControl(false, cfg);
            }
            
        }).on("click", ".cafe-at-geography>span", function (e) { //地理信息
            e.stopPropagation();
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
            } else {
                $(this).addClass("active");
            }
            if ("demlayer" == $(this).attr("gid")) {
                GIS.LayerControll.showControll(cfg.gisId, "baselayer", !$(this).hasClass("active"));
            } else if ($(this).hasClass("active") && "bianjielayer" == $(this).attr("gid")) {
                $(".cafe-at-geography span[gid='bianjielayer_noStr']").removeClass("active");
                GIS.LayerControll.showControll(cfg.gisId, "bianjielayer_noStr", false);
            } else if ($(this).hasClass("active") && "bianjielayer_noStr" == $(this).attr("gid")) {
                $(".cafe-at-geography span[gid='bianjielayer']").removeClass("active");
                GIS.LayerControll.showControll(cfg.gisId, "bianjielayer", false);
            }
            GIS.LayerControll.showControll(cfg.gisId, $(this).attr("gid"), $(this).hasClass("active"));
        })
    }
	var drawlyboundry = function(active,id,cfg,layerid){
		GIS.LayerControll.deleteLayer(cfg.gisId,layerid)
		if(!active){
			return;
		}
		let defaultobj = {
			style: {
				lineWidth : 2,
				fillStyle: "rgba(255,255,255,0)",
				strokeStyle: "rgba(250,43,255,1)"
			}
		}
		let lines = ["R12","R4","R5"]
		let styleset = {
			"R12":{
				wkid: 4326,
				style:{ strokeStyle: "rgba(77,152,228,1)", lineWidth: 4 }
			},
			"R4":{
				wkid: 4326,
				style:{ strokeStyle: "rgba(77,152,228,1)", lineWidth: 2 }
			},
			"R5":{
				wkid: 4326,
				style:{ strokeStyle: "rgba(77,152,228,1)", lineWidth: 2 }
			}
		}
		$.getJSON("/business/HHLY.json", function (obj) {
			let data = obj[id];
			let options = styleset[id]?styleset[id]:defaultobj;
			let areas = Object.values(data);
			if(lines.indexOf(id) != -1){
				GIS.Graphic.showPolyline(cfg.gisId, layerid, areas, options);
			}else{
				GIS.Graphic.showPolygon(cfg.gisId, layerid, areas, options);
			}
		})
	}
	var controllayer = function(active,id,cfg){
		GIS.LayerControll.showControll(cfg.gisId,id,active);
		if(id == "satellite_china"){
			GIS.LayerControll.showControll(cfg.gisId,"labelLayer_satellite",active);
			GIS.LayerControll.showControll(cfg.gisId,"tj_xq_text_satellite",active);
			GIS.LayerControll.showControll(cfg.gisId,"labelLayer",!active);
			GIS.LayerControll.showControll(cfg.gisId,"tj_xq_text",!active);
		}
	}
    // 风羽控制
    var windBarControl = function (selected, cfg) {
        var selectLayerId = [];
        $(".cafe-at-station .cas-station.active").each(function(index){
            var id = "WIND" + $(this).attr('type');
            GLMap.layerIds.forEach(function(layerId) {
                if (layerId == id)
                    selectLayerId.push(layerId);
            })
        })
        GIS.LayerControll.showControll(cfg.gisId, selectLayerId, selected);
    }
    // 风速控制
    var windSpeedControl = function (selected, cfg) {
        var selectLayerId = [];
        $(".cafe-at-station .cas-station.active").each(function(index){
            var id = "WIND" + $(this).attr('type') + 'TxtBg';
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId == id)
                    selectLayerId.push(layerId);
            })
        })
        GIS.LayerControll.showControll(cfg.gisId, selectLayerId, selected);
    }
    var CFToolsbar = function (settings) {
        var options = {
            appendTo: null, //控件所在容器
            gisId: null, //GIS的ID
            call: null //控件点击事件
        };
        this.config = $.extend({}, options, settings);
        var $container = $(this.config.appendTo);
        this.$drop = bulidHtml(this.config);
        _eves(this.$drop, this.config);

        if (this.config.appendTo) {
            $container.show().prepend(this.$drop);
        }
    }

    CFToolsbar.prototype = {
        disabledBtn: function (ids) {
            this.$drop.find("li").each(function () {
                if (-1 != $.inArray($(this).attr("id"), ids)) {
                    $(this).removeClass("active").addClass("disabled");
                }
            });
        },
        activeBtn: function (ids, isNoSelected) {
            this.$drop.find("li").each(function () {
                if (-1 != $.inArray($(this).attr("id"), ids)) {
                    $(this).removeClass("disabled");
                    if (!isNoSelected) $(this).addClass("active");
                }
            });
        },
        removeActive: function (ids) {
            this.$drop.find("li").each(function () {
                if (-1 != $.inArray($(this).attr("id"), ids)) {
                    $(this).removeClass("active");
                }
            });
        },
        removeChildActive: function (ids) {
            this.$drop.find("li>div span").each(function () {
                if (-1 != $.inArray($(this).attr("id"), ids)) {
                    $(this).removeClass("active");
                }
            });
        },
        getArea: function () {
            var $area = this.$drop.find(".cafe-at-zoneswitch>span.active");
            return {
                areaCode: $area.attr("areacode"),
                areaId: $area.attr("areaid")
            };
        },
        getUnActiveStationType: function () {
            var st = [];
            this.$drop.find(".cafe-at-station .cas-station").each(function () {
                if (!$(this).hasClass('active'))
                    st.push($(this).attr("type"));
            });
            return st;
        },
        getStationType: function () {
            var st = [];
            this.$drop.find(".cafe-at-station .cas-station.active").each(function () {
                st.push($(this).attr("type"));
            });
            return st.join(",");
        },
        setStationType: function (type) {
            this.$drop.find(".cafe-at-station .cas-station[type$='" + type + "']").show().siblings(".cas-station:not(span[type$='" + type + "'])").hide();
        },
        setStationSelFun: function (fun) {
            if (!this.config.stationSelFun) {
                this.config.stationSelFun = [];
            }
            this.config.stationSelFun.push(fun);
        },
        setAreaSelFun: function (fun) {
            this.config.areaSelFun = fun;
        },
        hideDemlayer: function () {
            var $demlayer = this.$drop.find(".cafe-at-geography>span[gid='demlayer']");
            if ($demlayer.hasClass("active")) {
                $demlayer.click();
            }
        },
        isActive: function(id) {
            return this.$drop.find(".cafe-at-station .cas-station.active").length === 0?false:true;
        },
        isToolActive: function(id) {
            return this.$drop.find('.cafe-at-gistools span[gid='+id+']').hasClass('active');
         },
        trigger: function (id) {
            this.$drop.find("#" + id).click();
        }
    };

    CafeJS.CFToolsbar = function (settings) {
        $(window).unbind("click").bind("click",function(event){
            var elem = event.target;
			debugger
            if(elem.id != "location" && elem.id != "layerManager"&& !$(elem).closest(".cafe-at-layerManager").length == 1&& elem.id != "station" && elem.id != "gistools"&& elem.id != "importantCG"){
                $(".cafe-busis-toolsbar-right li >div").hide();
                $(".cafe-busis-toolsbar-right li[id !='importantCG']").removeClass("active");
            }
        })
        var drop = new CFToolsbar(settings);
        return drop;
    }
})
